<?php


namespace app\admin\model;


use app\sys\service\GateCli;
use GatewayClient\Gateway;
use think\Db;
use think\Log;
use think\Model;

class StaffTime extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * @param $staffNo
     * @param $_user
     */
    public static function saveTime($staffNo,$_user)
    {
        $device_id = isset($_user["device_id"])?$_user["device_id"]:"";
        $dayNum = strtotime(date("Y-m-d",time()));
        $staffTimeRes = StaffTime::where("create_day",$dayNum)->where("staff_no",$staffNo)->find();
        if(!$staffTimeRes){
            StaffTime::create(["create_day"=>$dayNum,"staff_no"=>$staffNo,"device_type"=>$device_id]);
        }else{
            $token = Token::where("staff_no",$staffNo)->where("device_type",$device_id)->find();
            if($token){
                $resTime = timeDiff(strtotime($staffTimeRes["create_time"]),strtotime($token["update_time"]));
                $staffTimeRes->data(["time_long"=> $staffTimeRes["time_long"]+$resTime["min"]])->save();
            }
        }
    }

    // 实时获取客服登录
    public static function saveTimeNow()
    {
        \think\facade\Log::info("saveTimeNow");
        Gateway::$registerAddress = \think\facade\Env::get("GATEWAY.REGIS_ADDRESS");
        if (Gateway::getAllUidCount() > 0){
            \think\facade\Log::info("saveTimeNow2");
            foreach (Gateway::getAllUidList() as $k => $v)
            {
                \think\facade\Log::info("saveTimeNow3");
                $type = substr($v, 0, 4);
                if($type == GateCli::$staPre){
                    \think\facade\Log::info("saveTimeNow");
                    $staffNo = substr($v, 4);
                    $device_id = "";
                    $dayNum = strtotime(date("Y-m-d",time()));
                    $staffTimeRes = StaffTime::where("create_day",$dayNum)->where("staff_no",$staffNo)->find();
                    if(!$staffTimeRes){
                        StaffTime::create(["create_day"=>$dayNum,"staff_no"=>$staffNo,"device_type"=>$device_id]);
                    }else{
                        $staffTimeRes->data(["time_long"=> Db::raw('time_long+1')])->save();
                    }
                }
            }
        }
    }
}